#include "Config.h"

#if OS_ALVA==OS_Android || OS_ALVA==OS_Linux
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#define LOG_TAG "DUMP"
#elif OS_ALVA == OS_iOS
#error "please add header files"
#elif OS_ALVA == OS_Windows
#include <io.h>
#include <direct.h>
#endif

#include "Log.h"

#include "Dump.h"

#if OS_ALVA == OS_Android
static char* dumpRoot = "/sdcard/Alva/";
#elif OS_ALVA == OS_iOS
static char* dumpRoot = "";
#elif OS_ALVA == OS_Windows
static char* dumpRoot = "./";
#elif OS_ALVA == OS_Linux
static char* dumpRoot = "/var/AlvaDump/";
#endif

static char file2open[1024];

char* dumpbuffer = NULL;

int dump_init_temp(size_t buffersize){
    //create dump folder
#if OS_ALVA==OS_Windows
    if(_access(dumpRoot, 00) != 0){
        _mkdir(dumpRoot);
#else
    if(access(dumpRoot, 00) != 0){
        mkdir(dumpRoot, S_IRUSR | S_IWUSR);
#endif
    }

    if(NULL != dumpbuffer)
        free(dumpbuffer);
    dumpbuffer = (char*)malloc(buffersize);

    return 0;
}

int dump_temp(char* filename, char* buf, long long size){

    FILE* file;

#if OS_ALVA==OS_Android || OS_ALVA==OS_Linux

    sprintf(file2open, "%s%s", dumpRoot, filename);
    file = fopen(file2open, "wb");

#elif OS_ALVA == OS_iOS

#error "please add file opt here"

#elif OS_ALVA == OS_Windows

    sprintf_s(file2open, 1024, "%s%s", dumpRoot, filename);
    fopen_s(&file, file2open, "wb");

#endif

    if(file == NULL){
        LOGE("can't open file: %s\n", file2open);
        return -1;
    }

    fwrite(buf, 1, (size_t)size, file);

    fclose(file);

    return 0;
}